package com.shop.cereshop.app.service.follow.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cereshop.app.dao.follow.CereBuyerFollowDAO;
import com.shop.cereshop.app.param.follow.BuyerFollowDTO;
import com.shop.cereshop.app.service.follow.CereBuyerFollowService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.domain.follow.CereBuyerFollow;
import com.shop.cereshop.commons.exception.CoBusinessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CereBuyerFollowServiceImpl extends ServiceImpl<CereBuyerFollowDAO, CereBuyerFollow> implements CereBuyerFollowService {

    @Resource
    private CereBuyerFollowDAO cereBuyerFollowDAO;

    @Override
    public void updateFollow(BuyerFollowDTO param, CereBuyerUser user) throws CoBusinessException {
        //参数校验
        if (param.getTargetId().equals(user.getBuyerUserId())) {
            throw new CoBusinessException(CoReturnFormat.USER_CHECK_ERROR);
        }
        if (! param.getFollowType().equals(IntegerEnum.NO.getCode()) || ! param.getFollowType().equals(IntegerEnum.YES.getCode())) {
            throw new CoBusinessException(CoReturnFormat.PARAM_INVALID);
        }
        //1、查询是否有关注记录
        CereBuyerFollow cereBuyerFollow = getOne(new LambdaQueryWrapper<CereBuyerFollow>()
                .eq(CereBuyerFollow::getBuyerUserId, user.getBuyerUserId())
                .eq(CereBuyerFollow::getTargetId, param.getTargetId())
        );
        //2、处理关注状态变更
        if (cereBuyerFollow != null) {
            //状态相等直接返回
            if (cereBuyerFollow.getState().equals(param.getState())) {
                return;
            }
            //不相等则更新
            cereBuyerFollow.setState(param.getState());
            cereBuyerFollowDAO.updateById(cereBuyerFollow);
        } else {
            //未存在
            if (param.getState().equals(IntegerEnum.YES.getCode())) {
                //首次关注
                CereBuyerFollow cereBuyerFollowNew = new CereBuyerFollow();
                cereBuyerFollowNew
                        .setBuyerUserId(user.getBuyerUserId())
                        .setTargetId(param.getTargetId())
                        .setFollowType(param.getFollowType())
                        .setState(param.getState());
                cereBuyerFollowDAO.insert(cereBuyerFollowNew);
            }
        }
    }
}
